#!/usr/bin/env python

import os
import datetime

class Garmin(object):
    '''Garmin class
    
    @author Julot <andy.julot@gmail.com>
    @since Monday, February 20, 2012. 02:09 PM'''
    
    dateTime = None
    depth = None
    latitude = None
    longitude = None
    
    def add(self, data):
        data = data.strip()
        if data.find('$GPGLL') >= 0:
            self._processGpgll(data)
        elif data.find('$SDDBT') >= 0:
            self._processSdbbt(data)
        
    def _processSdbbt(self, data):
        d = data.split(',')
        self.depth = _ValueUnit(d[3], d[4])
    
    def _processGpgll(self, data):
        d = data.split(',')
        now = datetime.datetime.now()
        self.dateTime = datetime.datetime(now.year, now.month, now.day,
                                          int(d[5][0:2]), int(d[5][2:4]),
                                          int(d[5][4:6]))
        pos = d[1].find('.')
        self.latitude = _Coordinate(d[1][:pos - 2], d[1][pos - 2:], d[2])
        pos = d[3].find('.')
        self.longitude = _Coordinate(d[3][:pos - 2], d[3][pos - 2:], d[4])
    
    @property
    def completed(self):
        return (self.depth and self.dateTime and self.longitude and 
                self.longitude)
    
    def save(self):
        d = (self.dateTime.year, self.dateTime.month, self.dateTime.day)
        path = os.path.join('data', '%s-%02d-%02d.txt' % d)
        f  = "%s-%02d-%02d\t%02d:%02d:%02d\t"
        f += "%03d\t%07.4f\t%s\t"
        f += "%03d\t%07.4f\t%s\t"
        f += "%06.2f\t%s\n"
        d = (self.dateTime.year, self.dateTime.month, self.dateTime.day,
             self.dateTime.hour, self.dateTime.minute, self.dateTime.second,
             self.latitude.degree, self.latitude.minute, self.latitude.mark,
             self.longitude.degree, self.longitude.minute, self.longitude.mark,
             self.depth.value, self.depth.unit)
        data = open(path, 'a')
        data.write(f % d)
        data.close()

class _ValueUnit(object):
    '''Value Unit class
    
    @author Julot <andy.julot@gmail.com>
    @since Monday, February 20, 2012. 03:57 PM'''
    
    value = None
    unit = None
    
    def __init__(self, value, unit):
        self.value = float(value)
        self.unit = unit.strip()

class _Coordinate(object):
    '''Coordinate class
    
    @author Julot <andy.julot@gmail.com>
    @since Monday, February 20, 2012. 03:56 PM'''
    
    degree = None
    minute = None
    mark = None
    
    def __init__(self, degree, minute, mark):
        self.degree = int(degree)
        self.minute = float(minute)
        self.mark = mark.strip()
        